<?php
declare (strict_types = 1);

namespace app\api\controller;

use think\exception\ValidateException;

use app\common\model\{WorkLog};
use app\common\validate\{WorkLogValidate};

class WorkLogController extends BaseController
{
    private $workLogModel;

    public function __construct(WorkLog $workLogModel)
    {
        parent::initialize();
        $this->workLogModel = $workLogModel;
    }

    /** 新增日志 */
    public function addWorkLog()
    {
        $data = input('');

        try{
            validate(WorkLogValidate::class)->scene('add')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $data['submit_time'] = strtotime($data['submit']);

        $addFlag = $this->workLogModel->add($data);

        if($addFlag['code'] != 'ok'){
            $this->error_back($addFlag['msg']);
        }

        $this->success_back('新增成功');
    }

    /** 日志列表 */
    public function getWorkLogList()
    {
        $data = input('');

        try{
            validate(WorkLogValidate::class)->scene('list')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $where[] = ['user_id' , '=', $data['user_id']];
        $where[] = ['project_id' , '=', $data['project_id']];

        if(!empty($data['start_time']) && empty($data['end_time'])){
            $where[] = ['submit_time', '>', strtotime($data['start_time'])];
        }

        if(!empty($data['end_time']) && empty($data['start_time'])){
            $where[] = ['submit_time', '<', strtotime($data['end_time']) + 86399];
        }

        if(!empty($data['start_time']) && !empty($data['end_time'])){
            $where[] = ['submit_time', 'between', [strtotime($data['start_time']), strtotime($data['end_time']) + 86399]];
        }

        $list = $this->workLogModel->getList($where, 1, $data['page'], $data['limit'], '*', 'create_time DESC');

        if($list['code'] != 'ok'){
            $this->error_back('暂无数据');
        }

        $this->success_back('ok', $list['data']);
    }
}